/*
 * Copyright 2011-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.platform.core.util;

/**
 * Bit转换工具.
 *
 * @author liym
 * @since 2024-09-02 22:16 新建
 */
public final class BitUtils {

    private BitUtils() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * 将{@code byte}转换为{@code bit}，一个byte等于8个bit
     *
     * @param b byte
     * @return bit
     */
    public static byte[] byteToBits(byte b) {
        byte[] result = new byte[8];
        for (int i = 7; i >= 0; i--) {
            result[i] = (byte) ((b >> i) & 1);
        }
        return result;
    }

    /**
     * 将{@code bits}转换为{@code byte}
     *
     * @param bits bits
     * @return byte
     */
    public static byte bitsToByte(byte[] bits) {
        byte result = (byte) 0;
        for (int i = 0, l = bits.length; i < l; i++) {
            result = (byte) (result | bits[i] << i);
        }
        return result;
    }

}
